import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rxdart/rxdart.dart';
import '../models/news_item.dart';
import '../services/news_service.dart';
import '../services/mock_news_service.dart';

// 新闻服务Provider（带自动降级）
final newsServiceProvider = Provider<NewsService>((ref) {
  return NewsService();
});

// 模拟新闻服务Provider
final mockNewsServiceProvider = Provider<MockNewsService>((ref) {
  return MockNewsService();
});

// 新闻列表Provider（带错误处理和降级）
final newsListProvider = FutureProvider<List<NewsItem>>((ref) async {
  final newsService = ref.watch(newsServiceProvider);
  final mockService = ref.watch(mockNewsServiceProvider);

  try {
    return await newsService.fetchNews();
  } catch (e) {
    print('网络请求失败，使用模拟数据: $e');
    return await mockService.fetchNews();
  }
});

// 新闻详情Provider（带错误处理和降级）
final newsDetailProvider = FutureProvider.family<NewsItem, String>((ref, id) async {
  final newsService = ref.watch(newsServiceProvider);
  final mockService = ref.watch(mockNewsServiceProvider);

  try {
    return await newsService.fetchNewsDetail(id);
  } catch (e) {
    print('网络请求失败，使用模拟数据: $e');
    return await mockService.fetchNewsDetail(id);
  }
});

// 搜索控制器Provider（使用rxDart进行防抖）
final searchControllerProvider = Provider<BehaviorSubject<String>>((ref) {
  final controller = BehaviorSubject<String>.seeded('');
  ref.onDispose(() => controller.close());
  return controller;
});

// 搜索结果Provider（带防抖和降级）
final searchResultsProvider = StreamProvider<List<NewsItem>>((ref) {
  final searchController = ref.watch(searchControllerProvider);
  final newsService = ref.watch(newsServiceProvider);
  final mockService = ref.watch(mockNewsServiceProvider);

  // 使用rxDart的debounceTime实现搜索防抖
  return searchController
      .debounceTime(const Duration(milliseconds: 500))
      .distinct()
      .switchMap((query) {
        if (query.isEmpty) {
          return Stream.value(<NewsItem>[]);
        }

        return Stream.fromFuture(() async {
          try {
            return await newsService.searchNews(query);
          } catch (e) {
            print('搜索失败，使用模拟数据: $e');
            return await mockService.searchNews(query);
          }
        }());
      })
      .handleError((error) {
        print('搜索错误: $error');
        return <NewsItem>[];
      });
});

// 选中的新闻分类Provider
final selectedCategoryProvider = StateProvider<String?>((ref) => null);

// 过滤后的新闻列表Provider
final filteredNewsProvider = Provider<AsyncValue<List<NewsItem>>>((ref) {
  final newsAsync = ref.watch(newsListProvider);
  final selectedCategory = ref.watch(selectedCategoryProvider);

  return newsAsync.whenData((newsList) {
    if (selectedCategory == null || selectedCategory == '全部') {
      return newsList;
    }
    return newsList.where((news) => news.category == selectedCategory).toList();
  });
});
